<?php 

namespace Modules\Card\Traits;

use Modules\Card\Entities\CardAsset;

trait CardAssetable
{
    public function getCardTotal() 
    {
        return $this->card_assets()->sum('balance');
    }

    public function card_assets()
    {
        $resourceType = str_singular($this->table);
        return $this->hasMany('\Modules\Card\Entities\CardAsset', 'target_id')->where('target_type', $resourceType);
    }

    public function card_asset($type)
    {
        $asset = $this->card_assets()->where('type', $type)->first();

        if (is_null($asset)) {
            $asset = CardAsset::create([
                'target_id' => $this->id,
                'target_type' => str_singular($this->table),
                'type' => $type,
                'name' => config('asset.' . $type . '.name', $type),
                'precision' => config('asset.' . $type . '.precision', 0),
                'balance' => 0,
                'frozen' => 0
            ]);
        }

        return $asset;
    }
}
?>